package view;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.SystemColor;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.RowSorter;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.TitledBorder;
import javax.swing.table.TableCellEditor;

import com.alee.laf.WebLookAndFeel;
import com.alee.laf.button.WebButton;
import com.alee.laf.rootpane.WebFrame;
import com.alee.laf.toolbar.WebToolBar;
import com.jgoodies.forms.factories.FormFactory;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.RowSpec;

import controller.SellController;

import javax.swing.JTextArea;

import org.jdesktop.swingx.JXDatePicker;
import org.jdesktop.swingx.JXTable;
import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator;
import org.jdesktop.swingx.autocomplete.ComboBoxCellEditor;

import model.Database;
import model.DatePicker;
import model.Employee;
import model.NumberCellEditor;
import model.NumberRenderer;
import model.OptionMessenger;
import model.Partner;
import model.SellTableModel;
import model.StoreImages;
import model.FormatFactory;
import model.UICommand;

import javax.swing.JComboBox;

public class SellPanel extends JPanel {
	private static final long serialVersionUID = 9115061059829830487L;
	private JXTable table;
	private JTextField sumAmount;
	private JTextField sumTax;
	private JTextField sumMoney;
	private JTextField moneyPayment;
	private JPanel panel;
	private JTextField textBill;
	private Connection connect;
	private JComboBox<Employee> cbx_employee;
	private JXDatePicker datePicker;
	private JComboBox<Object> comboBoxType;
	private JComboBox<Object> comboBoxProvider;
	private JComboBox<Object> comboBoxID;
	private JComboBox<Object> comboBoxName;
	private JComboBox<Object> comboBoxUnit;
	private JTextField txtName;
	private JTextField txtAddress;
	private JTextField txtPhone;
	private JTextArea textArea;
	private JComboBox<String> cbxPmtOption;

	public SellPanel(SellTableModel tableModel, SellController control,
			boolean showToolBar) {
		this.setLayout(new BorderLayout(0, 0));

		JSplitPane splitPane = new JSplitPane();
		this.add(splitPane, BorderLayout.CENTER);
		splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
		splitPane.setResizeWeight(0.1);
		splitPane.setOneTouchExpandable(true);

		JPanel north = new JPanel();
		splitPane.setLeftComponent(north);
		north.setLayout(new BorderLayout(0, 0));

		JPanel detail = new JPanel();
		north.add(detail, BorderLayout.NORTH);
		detail.setBorder(new TitledBorder(null,
				"Chi ti\u1EBFt h\u00F3a \u0111\u01A1n", TitledBorder.LEADING,
				TitledBorder.TOP, null, SystemColor.textHighlight));
		FormLayout fl_detail = new FormLayout(new ColumnSpec[] {
				FormFactory.DEFAULT_COLSPEC, FormFactory.RELATED_GAP_COLSPEC,
				FormFactory.BUTTON_COLSPEC, FormFactory.RELATED_GAP_COLSPEC,
				FormFactory.DEFAULT_COLSPEC, FormFactory.RELATED_GAP_COLSPEC,
				FormFactory.DEFAULT_COLSPEC, FormFactory.RELATED_GAP_COLSPEC,
				FormFactory.DEFAULT_COLSPEC, FormFactory.RELATED_GAP_COLSPEC,
				ColumnSpec.decode("max(87dlu;pref)"),
				FormFactory.RELATED_GAP_COLSPEC,
				ColumnSpec.decode("right:default:grow"), },
				new RowSpec[] { FormFactory.DEFAULT_ROWSPEC, });
		detail.setLayout(fl_detail);

		JLabel lblMH = new JLabel("Mã HĐ");
		detail.add(lblMH, "1, 1, right, default");

		textBill = new JTextField(getIDBill());
		textBill.setBackground(Color.WHITE);
		textBill.setEditable(false);
		detail.add(textBill, "3, 1, fill, default");
		textBill.setColumns(18);

		JLabel lblNhnVinLp = new JLabel("Nhân viên lập");
		detail.add(lblNhnVinLp, "5, 1, right, default");

		cbx_employee = new JComboBox<Employee>();
		cbx_employee.setModel(loadDataEmpl());
		cbx_employee.setSelectedIndex(-1);
		cbx_employee.setPreferredSize(textBill.getPreferredSize());
		AutoCompleteDecorator.decorate(cbx_employee);
		detail.add(cbx_employee, "7, 1, fill, default");

		JLabel lblNgyLp = new JLabel("Ngày lập");
		detail.add(lblNgyLp, "9, 1, right, default");

		datePicker = DatePicker.createDatePicker(
				DatePicker.DEFAULT_WIDTH_COLUMN, DatePicker.DEFAULT_ICON);
		detail.add(datePicker, "11, 1");

		JPanel panel_2 = new JPanel();
		panel_2.setBorder(new TitledBorder(null, "Kh\u00E1ch h\u00E0ng",
				TitledBorder.LEADING, TitledBorder.TOP, null,
				SystemColor.textHighlight));
		north.add(panel_2, BorderLayout.CENTER);
		panel_2.setLayout(new BorderLayout(0, 7));

		JPanel khachHang = new JPanel();
		panel_2.add(khachHang, BorderLayout.NORTH);
		khachHang.setLayout(new FormLayout(new ColumnSpec[] {
				FormFactory.DEFAULT_COLSPEC, FormFactory.RELATED_GAP_COLSPEC,
				ColumnSpec.decode("max(77dlu;default):grow"),
				FormFactory.RELATED_GAP_COLSPEC,
				ColumnSpec.decode("max(15dlu;default)"),
				FormFactory.RELATED_GAP_COLSPEC,
				ColumnSpec.decode("default:grow"), }, new RowSpec[] {
				FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC, }));

		JLabel lblTnKhchHng = new JLabel("Tên KH");
		lblMH.setPreferredSize(lblTnKhchHng.getPreferredSize());
		khachHang.add(lblTnKhchHng, "1, 1, left, default");

		WebButton button = new WebButton("");
		button.setRolloverDecoratedOnly(true);
		button.setFocusable(false);
		button.setIcon(StoreImages.getIcon(StoreImages.NEW_BILL_ICON));
		button.setActionCommand("new");
		button.addActionListener(control);
		detail.add(button, "13, 1");

		txtName = new JTextField();
		khachHang.add(txtName, "3, 1, 5, 1, fill, default");
		txtName.setColumns(10);

		JLabel lblaCh = new JLabel("Địa chỉ");
		khachHang.add(lblaCh, "1, 3, left, default");

		txtAddress = new JTextField();
		khachHang.add(txtAddress, "3, 3, fill, default");
		txtAddress.setColumns(10);

		JLabel lblinThoi = new JLabel("Điện thoại");
		khachHang.add(lblinThoi, "5, 3, left, default");

		txtPhone = new JTextField();
		khachHang.add(txtPhone, "7, 3, fill, default");
		txtPhone.setColumns(10);

		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setViewportBorder(new TitledBorder(null, "Ghi ch\u00FA",
				TitledBorder.LEADING, TitledBorder.TOP, null,
				SystemColor.activeCaption));
		panel_2.add(scrollPane, BorderLayout.CENTER);

		textArea = new JTextArea();
		scrollPane.setViewportView(textArea);

		panel = new JPanel();
		splitPane.setRightComponent(panel);
		panel.setBorder(new TitledBorder(UIManager
				.getBorder("TitledBorder.border"),
				"Danh s\u00E1ch mua h\u00E0ng", TitledBorder.LEADING,
				TitledBorder.TOP, null, new Color(51, 153, 255)));
		panel.setLayout(new BorderLayout(0, 7));

		JScrollPane list = new JScrollPane();
		list.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
		list.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		panel.add(list, BorderLayout.CENTER);

		// TODO table
		table = new JXTable(tableModel);
		table.setSurrendersFocusOnKeystroke(true);
		table.setHorizontalScrollEnabled(true);
		table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
		table.getTableHeader().setReorderingAllowed(false);
		table.setFillsViewportHeight(true);
		list.setViewportView(table);

		// temp
		table.getColumnModel().getColumn(0)
				.setCellRenderer(new NumberRenderer());
		table.getTableHeader().setToolTipText("Test Tool Tip");

		final JPopupMenu popupMenu = new JPopupMenu();

		JMenuItem mntmngXut = new JMenuItem("Pack All");
		mntmngXut.setIcon(StoreImages.getIcon(StoreImages.LOGOUT_ICON));
		popupMenu.add(mntmngXut);

		JMenuItem mntmThot = new JMenuItem("Thoát");
		mntmThot.setIcon(StoreImages.getIcon(StoreImages.EXIT_ICON));
		popupMenu.add(mntmThot);

		// TODO cell editor
		table.setDefaultEditor(Double.class, new NumberCellEditor(
				new Double(0), control));
		table.setDefaultEditor(Integer.class, new NumberCellEditor(new Integer(
				0), control));

		// TODO combobox cell editor
		this.comboBoxType = new JComboBox<Object>();
		this.comboBoxProvider = new JComboBox<Object>();
		this.comboBoxID = new JComboBox<Object>();
		this.comboBoxName = new JComboBox<Object>();
		this.comboBoxUnit = new JComboBox<Object>();

		AutoCompleteDecorator.decorate(this.comboBoxType);
		AutoCompleteDecorator.decorate(this.comboBoxProvider);
		AutoCompleteDecorator.decorate(this.comboBoxID);
		AutoCompleteDecorator.decorate(this.comboBoxName);
		AutoCompleteDecorator.decorate(this.comboBoxUnit);

		tableModel.createComboBox(comboBoxID, 1);
		tableModel.createComboBox(comboBoxType, 2);
		tableModel.createComboBox(comboBoxName, 3);
		tableModel.createComboBox(comboBoxProvider, 4);
		tableModel.createComboBox(comboBoxUnit, 5);

		table.getColumnModel().getColumn(1)
				.setCellEditor(new ComboBoxCellEditor(comboBoxID));
		table.getColumnModel().getColumn(3)
				.setCellEditor(new ComboBoxCellEditor(comboBoxName));
		table.getColumnModel().getColumn(2)
				.setCellEditor(new ComboBoxCellEditor(comboBoxType));
		table.getColumnModel().getColumn(4)
				.setCellEditor(new ComboBoxCellEditor(comboBoxProvider));
		table.getColumnModel().getColumn(5)
				.setCellEditor(new ComboBoxCellEditor(comboBoxUnit));

		// alignment center
		FormatFactory.formatHeader(table, SwingConstants.CENTER);
		FormatFactory.formatHighlighter(table, null);

		// TODO function
		JPanel paymentPanel = new JPanel();
		this.add(paymentPanel, BorderLayout.SOUTH);
		paymentPanel.setBorder(new TitledBorder(UIManager
				.getBorder("TitledBorder.border"), "Thanh to\u00E1n",
				TitledBorder.LEADING, TitledBorder.TOP, null,
				SystemColor.textHighlight));
		paymentPanel.setLayout(new FormLayout(new ColumnSpec[] {
				FormFactory.DEFAULT_COLSPEC, FormFactory.RELATED_GAP_COLSPEC,
				ColumnSpec.decode("default:grow"),
				FormFactory.RELATED_GAP_COLSPEC, FormFactory.DEFAULT_COLSPEC,
				FormFactory.RELATED_GAP_COLSPEC,
				ColumnSpec.decode("default:grow"), }, new RowSpec[] {
				FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC, }));

		JPanel thanhToan = new JPanel();
		this.add(thanhToan, BorderLayout.SOUTH);
		thanhToan.setBorder(new TitledBorder(null, "Thanh to\u00E1n",
				TitledBorder.LEADING, TitledBorder.TOP, null,
				SystemColor.textHighlight));
		thanhToan
				.setLayout(new FormLayout(new ColumnSpec[] {
						FormFactory.DEFAULT_COLSPEC,
						FormFactory.RELATED_GAP_COLSPEC,
						ColumnSpec.decode("max(15dlu;default):grow"),
						FormFactory.RELATED_GAP_COLSPEC,
						FormFactory.DEFAULT_COLSPEC,
						FormFactory.RELATED_GAP_COLSPEC,
						ColumnSpec.decode("default:grow"),
						FormFactory.RELATED_GAP_COLSPEC,
						FormFactory.DEFAULT_COLSPEC,
						FormFactory.RELATED_GAP_COLSPEC,
						ColumnSpec.decode("default:grow"), }, new RowSpec[] {
						FormFactory.RELATED_GAP_ROWSPEC,
						FormFactory.DEFAULT_ROWSPEC,
						FormFactory.RELATED_GAP_ROWSPEC,
						FormFactory.DEFAULT_ROWSPEC,
						FormFactory.RELATED_GAP_ROWSPEC,
						FormFactory.DEFAULT_ROWSPEC, }));

		JLabel lblTngSLng = new JLabel("Tổng số lượng");
		thanhToan.add(lblTngSLng, "1, 2, left, default");

		sumAmount = new JTextField();
		sumAmount.setEditable(false);
		sumAmount.setColumns(2);
		thanhToan.add(sumAmount, "3, 2, fill, default");

		JLabel lblTinThu = new JLabel("Tổng thuế");
		thanhToan.add(lblTinThu, "5, 2, left, default");

		sumTax = new JTextField();
		sumTax.setEditable(false);
		thanhToan.add(sumTax, "7, 2, fill, default");
		sumTax.setColumns(10);

		JLabel lblTngCng = new JLabel("Tổng tiền");
		thanhToan.add(lblTngCng, "9, 2, left, default");

		sumMoney = new JTextField();
		sumMoney.setEditable(false);
		thanhToan.add(sumMoney, "11, 2, fill, default");
		sumMoney.setColumns(10);

		JLabel lblTinThanhTon = new JLabel("Thành tiền");
		thanhToan.add(lblTinThanhTon, "1, 4, left, default");

		moneyPayment = new JTextField();
		moneyPayment.setEditable(false);
		thanhToan.add(moneyPayment, "3, 4, fill, default");
		moneyPayment.setColumns(10);

		JLabel lblTinThanhTon_1 = new JLabel("Thanh toán");
		thanhToan.add(lblTinThanhTon_1, "5, 4, right, default");

		cbxPmtOption = new JComboBox<String>();
		ComboBoxModel<String> aModel = new DefaultComboBoxModel<>(new String[] {
				"Tiền mặt", "Chuyển khoản" });
		cbxPmtOption.setModel(aModel);
		cbxPmtOption.setEditable(true);
		AutoCompleteDecorator.decorate(cbxPmtOption);
		cbxPmtOption.setBackground(Color.WHITE);
		thanhToan.add(cbxPmtOption, "7, 4, 5, 1, fill, default");

		if (showToolBar)
			addToolBar(control);
	}

	public int[] getSelectedRows() {
		int[] selectedRow = table.getSelectedRows();
		int[] realRow = new int[table.getSelectedRowCount()];
		for (int i = 0; i < realRow.length; i++) {
			realRow[i] = table.convertRowIndexToModel(selectedRow[i]);
		}
		return realRow;
	}

	public void setValue(String sumAmount, String sumTax, String sumMoney,
			String sumPayment) {
		this.sumAmount.setText(sumAmount);
		this.sumTax.setText(sumTax);
		this.sumMoney.setText(sumMoney);
		this.moneyPayment.setText(sumPayment);
	}

	private void addToolBar(SellController control) {
		// TODO tool bar
		WebToolBar toolBar = new WebToolBar();
		FormatFactory.formatToolBar(toolBar);
		panel.add(toolBar, BorderLayout.EAST);

		toolBar.add(FormatFactory.createButtonToolBar("Thêm", UICommand.ADD_CMD,
				StoreImages.getIcon(StoreImages.NEW_ICON), control));
		toolBar.add(FormatFactory.createButtonToolBar("Refresh",
				UICommand.REFRESH_CMD,
				StoreImages.getIcon(StoreImages.REFRESH_ICON), control));
		toolBar.add(FormatFactory.createButtonToolBar("Xóa", UICommand.DELETE_CMD,
				StoreImages.getIcon(StoreImages.DELETE_ICON), control));
		toolBar.add(FormatFactory.createButtonToolBar("Tính tiền",
				UICommand.COMPUTING_CMD,
				StoreImages.getIcon(StoreImages.DOLLAR_ICON), control));
		toolBar.add(FormatFactory.createButtonToolBar("Lưu", UICommand.SAVE_CMD,
				StoreImages.getIcon(StoreImages.SAVE_ICON), control));
	}

	public void clearSortedRow() {
		RowSorter<?> rs = table.getRowSorter();
		rs.setSortKeys(null);
	}

	public void editCellAt(int row, int column) {
		table.editCellAt(row, column);
		System.out.println(table.getEditingRow());
	}

	public void stopCellEditing() {
		TableCellEditor cellEditor = table.getCellEditor();
		if (cellEditor != null)
			cellEditor.stopCellEditing();
	}

	private DefaultComboBoxModel<Employee> loadDataEmpl() {
		try {
			Connection connect = null;

			if (connect == null)
				connect = Database.connect();

			PreparedStatement pre = connect
					.prepareStatement("SELECT * FROM employee INNER JOIN regency ON employee.regency = regency.name "
							+ "WHERE regency.id = 'BHG' ORDER BY employee.last_name ASC");
			ResultSet rs = pre.executeQuery();

			DefaultComboBoxModel<Employee> model = new DefaultComboBoxModel<>();
			while (rs.next()) {
				Employee e = new Employee();
				e.setId(rs.getInt("id_empl"));
				e.setFirstName(rs.getString("first_name"));
				e.setLastName(rs.getString("last_name"));
				e.setBirthday(rs.getDate("birthday"));
				e.setSex(rs.getString("sex"));
				e.setIdent(rs.getString("identification"));
				e.setAddress(rs.getString("address"));
				e.setPhone(rs.getString("phone"));
				e.setDateBegin(rs.getDate("date_begin"));
				e.setRegency(rs.getString("regency"));

				model.addElement(e);
			}
			return model;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	// TODO get id bill
	public String getIDBill() {
		try {
			if (connect == null)
				connect = Database.connect();

			PreparedStatement pre = connect
					.prepareStatement("SELECT max(id) + 1 FROM bill");
			ResultSet rs = pre.executeQuery();

			if (rs.first())
				return rs.getString(1);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return "00";
	}

	// TODO checkBill
	public boolean checkBill() {
		boolean result = true;
		if (this.cbx_employee.getSelectedIndex() == -1) {
			result = false;
			OptionMessenger.showMessageDialog(
					OptionMessenger.windowForComponent(this),
					"Chưa chọn nhân viên lập hóa đơn", "Lỗi",
					OptionMessenger.ERROR_MESSAGE);
		} else {
			JFormattedTextField textField = datePicker.getEditor();
			DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			try {
				dateFormat.parse(textField.getText());
			} catch (ParseException e) {
				result = false;
				OptionMessenger.showMessageDialog(
						OptionMessenger.windowForComponent(this),
						"Ngày chọn không phù hợp", "Lỗi",
						OptionMessenger.ERROR_MESSAGE);
			}
		}
		return result;
	}

	public void deleteAll() {
		this.textBill.setText(getIDBill());
		this.cbx_employee.setSelectedIndex(-1);
		this.datePicker.setDate(new Date());
		this.txtName.setText("");
		this.txtPhone.setText("");
		this.txtAddress.setText("");
		this.textArea.setText("");
	}

	// get data to save bill
	public Date getDate() {
		return datePicker.getDate();
	}

	public boolean checkPartner() {
		String parter = txtName.getText();
		if (parter.equals("")) {
			OptionMessenger.showMessageDialog(
					OptionMessenger.windowForComponent(this),
					"Tên nhà khách hàng không được rỗng", "Lỗi",
					OptionMessenger.ERROR_MESSAGE);
			return false;
		}
		return true;
	}

	public Partner getPartner() {
		Partner p = new Partner();
		p.setName(txtName.getText());
		p.setAddress(txtAddress.getText());
		p.setEmail("");
		p.setPhone(txtPhone.getText());
		p.setFax("");
		p.setNote(textArea.getText());
		return p;
	}

	public Employee getEmployee() {
		return (Employee) this.cbx_employee.getSelectedItem();
	}

	public static void main(String[] args) {
		try {
			UIManager.setLookAndFeel(new WebLookAndFeel());
		} catch (UnsupportedLookAndFeelException e) {
			e.printStackTrace();
		}
		// WebLookAndFeel.setDecorateFrames(true);
		WebFrame frame = new WebFrame();
		SellTableModel tableModel = new SellTableModel();
		SellController control = new SellController(tableModel);
		frame.getContentPane().add(control.getView());
		frame.pack();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);

		// WebLookAndFeel.setDecorateFrames(WebLookAndFeel.isDecorateFrames());
	}

	public String getPayment() {
		return (String) cbxPmtOption.getSelectedItem();
	}

}
